package com.cyy.base.service;

import com.cyy.base.dao.LabelDao;
import com.cyy.base.pojo.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 标签数据业务逻辑层
 */
@Service
public class LabelService {

    @Autowired
    private LabelDao labelDao;

    @Autowired
    private IdWorker idWorker;

    public List<Label> findAll(){
        return labelDao.findAll();
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Specification<Label> createSpecification(Map searchMap){
        return new Specification<Label>() {
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if(searchMap.get("labelname") != null && !"".equals(searchMap.get("labelname"))){
                    list.add( cb.like(root.get("labelname").as(String.class),"%" + searchMap.get("labelname").toString() + "%"));
                }
                if(searchMap.get("state") != null && !"".equals(searchMap.get("state"))){
                    list.add( cb.like(root.get("state").as(String.class),"%" + searchMap.get("state").toString() + "%"));
                }
                if(searchMap.get("recommend") != null && !"".equals(searchMap.get("recommend"))){
                    list.add( cb.like(root.get("recommend").as(String.class),"%" + searchMap.get("recommend").toString() + "%"));
                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }

    public List<Label> findAll(Map searchMap){
        Specification<Label> specification = createSpecification(searchMap);
        return labelDao.findAll(specification);
    }


    /**
     * 标签分页查询方法
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public Page<Label> findSearch(Map searchMap,int page,int size){
        Specification<Label> specification = this.createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page-1,size);
        return labelDao.findAll(specification,pageRequest);
    }

    /**
     * 根据ID查询实体
     * @param id
     * @return
     */
    public Label findById(String id) {
        return labelDao.findById(id).get();
    }
}
